package com.zros.modules.business.controller;


import io.swagger.annotations.ApiOperation;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zros.common.api.vo.PageResult;
import com.zros.common.api.vo.Result;
import com.zros.common.exception.JeecgBootException;
import com.zros.modules.business.entity.Course;
import com.zros.modules.business.entity.Department;
import com.zros.modules.business.service.ICourseService;
import com.zros.modules.business.service.IDepartmentService;
import com.zros.modules.business.vo.DepartmentVo;
import com.zros.modules.shiro.authc.util.JwtUtil;
import com.zros.modules.system.dto.UserInfo;
import com.zros.modules.system.service.IUserService;

/**
 * <p>
 * 科系表 前端控制器
 * </p>
 *
 * @author pangyinqiang
 * @since 2019-04-20
 */
@RestController
@RequestMapping("/business/department")
@PropertySource("classpath:config.properties")
public class DepartmentController {
	
	@Value("${authority.campusKey}")
	private String authorityCampusKey;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IDepartmentService departmentService;
	
	@Autowired
	private ICourseService courseService;
	
	/**
	 * 分页查询科系
	 */
	@ApiOperation(value = "分页查询科系")
	@RequiresPermissions("business:department:list")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public PageResult<DepartmentVo> queryPageList(HttpServletRequest request, Page<DepartmentVo> page, Department department) 
	{
		//获取当前用户
		UserInfo currentUser = queryCurrentUser(request,"queryDepartment");
		//获取数据权限key
		String dataResourceKey = currentUser.getDataResourceKey();
		if(StringUtils.isEmpty(dataResourceKey))
		{
			throw new JeecgBootException("数据权限查询不到！请联系管理员！");
		}
		
		//校区权限，查询自己所属校区渠道类型
		if(authorityCampusKey.equals(dataResourceKey))
		{
			department.setUserId(currentUser.getId());
		}
		
		Page<DepartmentVo> pageDepartment = departmentService.queryList(page,department);
        PageResult<DepartmentVo> pageResult = new PageResult<DepartmentVo>(pageDepartment.getTotal(), pageDepartment.getRecords());
		return pageResult;
	}
	
	/**
	 * 添加科系
	 */
	@ApiOperation(value = "添加科系")
	@RequiresPermissions("business:department:list")
	@PostMapping("/create")
	public Result<?> create(@RequestBody Department department) 
	{
		QueryWrapper<Department> ew = new QueryWrapper<>();
        ew.eq("department_name", department.getDepartmentName()).
        	eq("department_flag", department.getDepartmentFlag());
        List<Department> roleList = departmentService.list(ew);
        if (!CollectionUtils.isEmpty(roleList)) {
            throw new JeecgBootException("科系名称在该校区中已经存在！");
        }
		
		return new Result<>().success(departmentService.save(department) ? "添加成功" : "添加失败，请重试");
	}

	/**
	 * 修改科系
	 */
	@ApiOperation(value = "修改科系")
	@RequiresPermissions("business:department:list")
	@PostMapping("/update")
	public Result<?> update(@RequestBody Department department) 
	{
		QueryWrapper<Department> ew = new QueryWrapper<>();
        ew.ne("department_id", department.getDepartmentId()).
        	eq("department_name", department.getDepartmentName()).
        	eq("department_flag", department.getDepartmentFlag());
        List<Department> roleList = departmentService.list(ew);
        if (!CollectionUtils.isEmpty(roleList)) {
            throw new JeecgBootException("科系名称在该校区中已经存在！");
        }
		
		return new Result<>().success(departmentService.updateById(department) ? "修改成功" : "修改失败，请重试");
	}

	/**
	 * 删除科系
	 */
	@ApiOperation(value = "删除科系")
	@RequiresPermissions("business:department:list")
	@PostMapping("/delete/{id}")
	public Result<?> delete(@PathVariable("id") Long id) {
		if (null == id) {
			return new Result<>().error("ID不能为空");
		}
		
		QueryWrapper<Course> ew = new QueryWrapper<>();
		ew.eq("department_id", id);
		List<Course> roleList = courseService.list(ew);
		if (!CollectionUtils.isEmpty(roleList)) {
			throw new JeecgBootException("该科系包含课程，不可删除！");
		}
		
		return new Result<>().success(departmentService.removeById(id) ? "删除成功" : "删除失败，请重试");
	}
	
	/**
	 *  获取当前用户
	 */
	UserInfo queryCurrentUser(HttpServletRequest request,String queryMethod)
	{
		UserInfo currentUser = new UserInfo();
		String userAccount = JwtUtil.getUserAccountByToken(request);
		currentUser = userService.queryUserInfoByAccount(userAccount,queryMethod);
		
		return currentUser;
	}
}
